
package com.jxccp.ui.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.BuildConfig;
import com.jxccp.ui.JXConstants;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;

public class JXLeaveMsgActivity extends JXBaseActivity implements OnClickListener {

    /**
     * 留言类型
     * 0：在线留言（app不适用)
     * 1：客服未响应
     * 2：客服离线
     */
    public static final int LEAVE_MSG_ONLINE = 0;

    public static final int LEAVE_MSG_AGNET_NO_RESPONSE = 1;

    public static final int LEAVE_MSG_AGNET_OFFLINE = 2;

    LinearLayout rootView;

    WebView webView;

    ProgressBar web_pb;

    ImageView backView;

    String url;

    String skillId;

    public ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public ValueCallback<Uri> mUploadMessage;
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    private final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jx_activity_leave_msg);

        rootView = (LinearLayout)findViewById(R.id.ll_container);
        web_pb = (ProgressBar)findViewById(R.id.web_pb);
        backView = (ImageView)findViewById(R.id.iv_left);
        backView.setOnClickListener(this);

        if (JXUiHelper.getInstance().getmTitleBgColorId() != JXUiHelper.INVALID_INT) {
            findViewById(R.id.rl_root).setBackgroundColor(getResources().getColor(JXUiHelper.getInstance().getmTitleBgColorId()));
        }

        if (JXUiHelper.getInstance().getmTitleTextColorResId() != JXUiHelper.INVALID_INT) {
            ((TextView)findViewById(R.id.tv_actionTitle)).setTextColor(
                    getResources().getColor(JXUiHelper.getInstance().getmTitleTextColorResId()));
        }

        if (JXUiHelper.getInstance().getmTitleLeftImgResId() != JXUiHelper.INVALID_INT) {
            ((ImageView)findViewById(R.id.iv_left)).setImageResource(JXUiHelper.getInstance().getmTitleLeftImgResId());
        }

        skillId = getIntent().getStringExtra(JXConstants.EXTRA_SKILLS_ID);

        int leaveMsgType = getIntent().getIntExtra(JXConstants.EXTRA_LEAVE_MSG_TYPE,LEAVE_MSG_AGNET_OFFLINE);

        url = JXImManager.McsUser.getInstance().getLeaveMsgWebUrl(skillId, JXUiHelper.getInstance().getSuborgId(),leaveMsgType);
        if (BuildConfig.BUILD_TYPE.equals("debug")){
            JXLog.d("[JXLeaveMsgActivity.onCreate] leave msg url = "+url);
        }
        init(url);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init(String address) {
        webView = (WebView)findViewById(R.id.webView);
        // 启用支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        // 优先使用缓存
//        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);

        webView.getSettings().setDomStorageEnabled(true);

        // WebView加载web资源
        webView.loadUrl(address);

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error){
                final AlertDialog.Builder builder = new AlertDialog.Builder(JXLeaveMsgActivity.this);
                builder.setMessage(R.string.jx_notification_error_ssl_cert_invalid);
                builder.setPositiveButton(R.string.jx_continue, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.proceed();
                    }
                });
                builder.setNegativeButton(R.string.jx_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    web_pb.setVisibility(View.GONE);
                } else {
                    if (View.INVISIBLE == web_pb.getVisibility()) {
                        web_pb.setVisibility(View.VISIBLE);
                    }
                    web_pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onCloseWindow(WebView window) {
                JXLog.d("on close window event");
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        JXLeaveMsgActivity.this.finish();
                    }
                }, 500);
                super.onCloseWindow(window);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

                builder.setMessage(message)
                        .setPositiveButton(getString(R.string.jx_confirm), null);
                // 禁止响应按back键的事件
                builder.setCancelable(false);
                AlertDialog dialog = builder.create();
                dialog.show();
                result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
                return true;
            }

            // For Android < 5.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            // For Android => 5.0
            public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> uploadMsg,
                                              WebChromeClient.FileChooserParams fileChooserParams) {
                onenFileChooseImpleForAndroid(uploadMsg);
                return true;
            }

        });

    }

    /**
     * android 5.0 以下开启图片选择（原生）
     *
     * 可以自己改图片选择框架。
     */
    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    /**
     * android 5.0(含) 以上开启图片选择（原生）
     *
     * 可以自己改图片选择框架。
     */
    private void onenFileChooseImpleForAndroid(ValueCallback<Uri[]> filePathCallback) {
        mUploadMessageForAndroid5 = filePathCallback;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("*/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri result = (data == null || resultCode != Activity.RESULT_OK) ? null: data.getData();
        if (result !=null){
            switch (requestCode){
                case FILE_CHOOSER_RESULT_CODE:  //android 5.0以下 选择图片回调

                    if (null == mUploadMessage)
                        return;
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;

                    break;

                case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:  //android 5.0(含) 以上 选择图片回调

                    if (null == mUploadMessageForAndroid5)
                        return;
                    if (result != null) {
                        mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
                    } else {
                        mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
                    }
                    mUploadMessageForAndroid5 = null;

                    break;
            }
        }else {
            if (mUploadMessage != null){
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            if (mUploadMessageForAndroid5 != null){
                mUploadMessageForAndroid5.onReceiveValue(null);
                mUploadMessageForAndroid5 = null;
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_left) {
            finish();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //webView资源释放
        if(rootView != null){
            rootView.removeAllViews();
        }
        if(webView != null){
            webView.removeAllViews();
            webView.destroy();
        }
    }
}
